#!/bin/bash
#
# Install subversion from yum repository and create user.
#    - svn/svn
#

echo "================================================================="
echo "Install subversion ($SERVER_NAME): begin"

SUBVERSION_HOME=/$SERVER_NAME/subversion

source $COMMON_FUNC > /dev/null 2>&1
if [ $? -gt 0 ]; then
    echo "Error: This script requires common-func.bash"
    exit 1
fi

isRoot

echo "Installing subversion software from yum repository"
yum install -y mod_dav_svn subversion

# creating system user/group for subversion
user_exists svn
if [ $? -eq 1 ]; 
then
    echo "Creating system user svn"
    useradd -r svn
else
    echo "System user svn already exists, nothing to do"
fi

echo "Creating home directory for subversion"
mkdir -p $SUBVERSION_HOME/etc
mkdir -p $SUBVERSION_HOME/svn

echo "Creating root link (/svn) to $SUBVERSION_HOME/svn"
ln -s $SUBVERSION_HOME/svn /svn

echo "Copying over subversion resources (passwd/authz)"
cp $RESOURCES_DIR/svn/passwd $SUBVERSION_HOME/etc/.
cp $RESOURCES_DIR/svn/authz $SUBVERSION_HOME/etc/.

echo "Applying permissions for $SUBVERSION_HOME"
chown -R svn:svn $SUBVERSION_HOME
chmod -R 770 $SUBVERSION_HOME

echo "Creating respository at /svn"
su svn -c "svnadmin create /svn"
if [ ! $? -eq 0 ];
then
    echo "Error creating repository at /svn"
    exit 1
else
    echo "Subversion repository created at /svn"
fi

echo "Backing up original svnserve.conf"
backup /svn/conf/svnserve.conf
if [ ! $? -eq 0 ]
then
    echo "Error: Encountered error in backing up of /svn/conf/svnserve.conf."
    pause '> Press [ENTER] to continue or [CTRL-C] to exit. Exiting will not install the new svnserve.conf file.'
fi

echo "Installing new /svn/conf/svnserve.conf"
su svn -c "rm -Rf /svn/conf/svnserve.conf"
su svn -c "cp $RESOURCES_DIR/svn/svnserve.conf /svn/conf/svnserve.conf"

echo "Creating iptables for svnserve (port 3690)"
open_port 3690
if [ ! $? -eq 0 ];
then
    echo "Encountered error during open_port 3690"
    pause '> Press [ENTER] to continue or [CTRL-C] to exit'
fi

echo "Install subversion: done"
echo "================================================================="
